package net.j4love.dubbo.serialize;

import com.alibaba.fastjson.JSON;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author He Peng
 * @create 2017-05-29 1:14
 * @update 2017-05-29 1:14
 * @updatedesc : 更新说明
 * @see
 */
public class JSONSerialize {

    public static void main(String[] args) throws UnsupportedEncodingException {

        Student student = new Student();
        List<Hobby> hobbies = new ArrayList<>();
        hobbies.add(new Hobby().setDesc("学英语"));
        hobbies.add(new Hobby().setDesc("玩游戏"));
        hobbies.add(new Hobby().setDesc("打篮球"));
        hobbies.add(new Hobby().setDesc("吐槽"));

        student.setName("小明")
                .setAge(12)
                .setGender("男")
                .setHobbies(hobbies);

        byte[] bytes = serialize(student, "UTF-8");
        System.err.println("byte size : " + bytes.length); // 134

        Student object = deserialize(bytes, "UTF-8", Student.class);

        if (object.equals(student)) {
            System.err.println(object);
        }

    }

    private static String detaultCharset(String charset) {
        if (charset == null || "".equals(charset)) {
            return "UTF-8";
        }
        return charset;
    }

    public static byte[] serialize(Object object,String charset) throws UnsupportedEncodingException {

        charset = detaultCharset(charset);
        String jsonObject = JSON.toJSONString(object);
        return jsonObject.getBytes(charset);
    }

    public static <T> T deserialize(byte[] bytes,String charset,Class<T> tClass) throws UnsupportedEncodingException {
        charset = detaultCharset(charset);
        String jsonObject = new String(bytes, charset);
        return JSON.parseObject(jsonObject,tClass);
    }
}
